package com.berrontech.asbog;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * Create by levent8421 2021/4/8 18:09
 * ApplicationConfig
 * Application config
 *
 * @author levent8421
 */

public class ApplicationConfig {
    private static final String FILE_NAME = "config.json";
    private static final String TAG = "ApplicationConfig";
    private static final String DEFAULT_URL = "http://192.168.1.100:5601/#/asbog";
    private static final String DEFAULT_PREFIX = "S1-";
    private static final Boolean DEFAULT_DISPLAY_REVERSE = false;
    private Context context;

    public static ApplicationConfig loadFromDisk(Context context) throws IOException {
        final ApplicationConfig config = new ApplicationConfig();
        config.context = context;
        return config.loadConfig();
    }


    private ApplicationConfig() {

    }

    private String url;
    private String prefix;
    private Boolean displayReverse;

    private ApplicationConfig loadConfig() throws IOException {
        final File configFile = getConfigFile();
        if (!configFile.isFile()) {
            Log.e(TAG, "Config file[" + configFile.getAbsolutePath() + "] is not a file!");
            this.url = DEFAULT_URL;
            this.prefix = DEFAULT_PREFIX;
            this.displayReverse = DEFAULT_DISPLAY_REVERSE;
            return this;
        }
        final byte[] bytes = FileUtils.readFileToByteArray(configFile);
        final ApplicationConfig newConfig = JSON.parseObject(bytes, getClass());
        newConfig.context = context;
        return newConfig;
    }

    private File getConfigFile() {
        final File selfRoot = context.getExternalFilesDir(null);
        final File dir = new File(selfRoot, "config");
        if (!dir.isDirectory()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException("Error on create config dir！");
            }
        }
        return new File(dir, FILE_NAME);
    }

    public void save() throws IOException {
        final byte[] bytes = JSON.toJSONBytes(this);
        final File file = getConfigFile();
        FileUtils.writeByteArrayToFile(file, bytes);
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public Boolean getDisplayReverse() {
        return displayReverse;
    }

    public void setDisplayReverse(Boolean displayReverse) {
        this.displayReverse = displayReverse;
    }
}
